<template>
    <view class="root">
        <label class="transform-identity">
            <text>转换为{{ userInfo.identity ? "乘客" : "车主" }}</text>
            <switch
                :disabled="certification.identity_status === 1"
                :checked="identitySwitchChecked.checked"
                @change="changeIdentity"
                color="#5487e5"
            />
        </label>
        <block v-if="userInfo.identity || certification.identity_status === 1">
            <picker
                mode="multiSelector"
                :range="pickers"
                range-key="name"
                :disabled="[1, 2].includes(certification.identity_status)"
                @columnchange="columnChangePicker"
                @change="changePicker"
            >
                <label class="picker-content">
                    <text class="title">选择路线</text>
                    <text class="value">
                        <text class="route">
                            {{ certification.route.name || "暂未选择路线" }}
                        </text>
                        <text class="company">
                            {{ certification.company.name || "" }}
                        </text>
                    </text>
                </label>
            </picker>

            <view
                class="credentials"
                v-for="(item, index) in credentials"
                :key="index"
            >
                <text class="title">
                    <text>{{ item.title }}</text>
                    <text v-if="item.tips" class="tips">{{ item.tips }}</text>
                </text>
                <view class="images">
                    <image
                        v-for="(image, imageIndex) in item.images"
                        :key="imageIndex"
                        @click="choosePhoto(image.key)"
                        mode="aspectFill"
                        :src="
                            certification.images[`img${image.key}`] || image.src
                        "
                    />
                </view>
            </view>

            <view class="options">
                <label
                    v-for="option in options"
                    :key="option.model"
                    @click="operation(option)"
                    class="option"
                >
                    <text class="title">{{ option.title }}</text>
                    <text class="value" v-if="option.type === 'actionSheet'">
                        {{ certification[option.model] ? "女" : "男" }}
                    </text>
                    <input
                        v-else
                        class="value"
                        v-model="certification[option.model]"
                        :maxlength="option.maxlength"
                        :disabled="
                            [1, 2].includes(certification.identity_status)
                        "
                        :placeholder="`请输入${option.title}`"
                    />
                </label>
            </view>

            <view class="rent-info">
                <text class="title">车辆贷款/租赁信息</text>
                <label class="explain">
                    <image
                        class="icon-warn"
                        src="/static/images/icon-warn.png"
                    />
                    <text>请如实填写车辆信息</text>
                </label>
            </view>

            <label class="option" @click="chooseIsRent">
                <text>该车辆是否租赁或者贷款购买</text>
                <label class="please-picker">
                    <text>{{ certification.isRent ? "是" : "否" }}</text>
                    <image
                        class="icon-more"
                        src="/static/images/icon-more_blue.png"
                    />
                </label>
            </label>

            <button
                :disabled="[1, 2].includes(certification.identity_status)"
                @click="submit"
                hover-class="tap-hover"
                class="btn-submit"
            >
                {{ status[certification.identity_status] }}
            </button>
        </block>
    </view>
</template>

<script lang="ts">
    import Vue from "vue";
    import Component from "vue-class-component";
    import {
        Certification as CertificationInterface,
        UserInfo,
    } from "../common/api.d";
    import { $config } from "@/common/index";
    import { Storage } from "@/libs/utils";

    @Component
    export default class Certification extends Vue {
        userInfo: UserInfo = Storage.get("userInfo");
        certification: CertificationInterface = {
            companies: [{ id: 0, name: "" }],
            routes: { 0: [{ id: 0, name: "" }] },
            company: { id: 0, name: "" },
            route: { id: 0, name: "" },
            images: {},
            isRent: false,
            identity_status: 0,
            userName: "",
            gender: 0,
            numberPlate: "",
            carType: "",
            color: "",
        };

        routeIndex: number = 0;
        companyIndex: number = 0;

        credentials: AnyObject[] = [
            {
                title: "身份证、驾驶证",

                images: [
                    { src: "/static/images/pic-idCard.png", key: 1 },
                    { src: "/static/images/pic-drivingLicense.png", key: 2 },
                ],
            },
            {
                title: "行驶证",
                images: [
                    { src: "/static/images/pic-drivingLicense_front.png", key: 3 },
                    { src: "/static/images/pic-drivingLicense_back.png", key: 4 },
                ],
            },
            {
                title: "车辆外观",
                tips: "(正前方车辆45°照片)",
                images: [{ src: "/static/images/pic-carExterior.png", key: 5 }],
            },
            {
                title: "运输证、从业资格证",
                images: [
                    { src: "/static/images/pic-transport.png", key: 6 },
                    { src: "/static/images/pic-qualification.png", key: 7 },
                ],
            },
        ];

        options: AnyObject[] = [
            {
                title: "车主姓名",
                model: "userName",
                maxlength: 9,
                type: "text",
            },
            {
                title: "性别",
                model: "gender",
                items: ["男", "女"],
                type: "actionSheet",
            },
            {
                title: "车牌号码",
                model: "numberPlate",
                maxlength: 9,
                type: "text",
            },
            {
                title: "车辆型号",
                model: "carType",
                maxlength: 18,
                type: "text",
            },
            {
                title: "车辆颜色",
                model: "color",
                maxlength: 9,
                type: "text",
            },
        ];

        status: Array<string> = ["提交信息", "审核中", "已审核通过", "重新提交"];

        public get pickers(): [AnyObject[], AnyObject[]] {
            const { certification, companyIndex } = this;
            const { companies, routes } = certification;

            return [companies, routes[companies[companyIndex].id]];
        }

        public get identitySwitchChecked(): { checked: boolean } {
            const { identity } = this.userInfo;
            const { identity_status } = this.certification;

            return {
                checked: !!identity || identity_status === 1,
            };
        }

        private onLoad(): void {
            uni.showLoading({ title: "Loading..." });
            this.request.get("api/idcard").then(({ data }) => {
                uni.hideLoading();
                this.certification = data;
            });
        }

        public async changeIdentity({ target }: AnyObject): Promise<void> {
            const { identity_status } = this.certification;

            const tips: AnyObject = {
                0: "你需要提交相关信息完成车主认证",
                1: "你的资料正在审核中",
                3: "资料审核失败，请检查相关证件或信息是否输入正确",
            };

            this.$set(this.userInfo, "identity", +target.value);

            if (tips[identity_status]) {
                this.userInfo.identity &&
                    uni.showToast({
                        title: tips[identity_status],
                        icon: "none",
                    });
                return;
            }

            uni.showModal({
                title: "提示",
                content: "确定后将关闭页面至小程序首页以完成身份切换，是否继续？",
                success: ({ confirm, cancel }) => {
                    if (cancel) {
                        this.$set(this.userInfo, "identity", +!target.value);
                        return;
                    }

                    if (confirm) {
                        this.request
                            .get("/api/changeIdentity")
                            .then(({ data }) => {
                                Storage.update("userInfo", data);
                                uni.reLaunch({ url: "/pages/home" });
                            })
                            .catch(({ data }) =>
                                this.$set(this.userInfo, "identity", +!target.value)
                            );
                    }
                },
            });
        }

        public changePicker({ detail }: AnyObject): void {
            this.certification.company = this.pickers[0][detail.value[0]];
            this.certification.route = this.pickers[1][detail.value[1]];
        }

        public columnChangePicker({ detail }: AnyObject): void {
            this[detail.column ? "routeIndex" : "companyIndex"] = detail.value;
        }

        public disableClick(): boolean {
            const {
                certification: { identity_status },
            } = this;

            if ([1, 2].includes(identity_status)) {
                uni.showToast({
                    title: `你的资料${
                        identity_status === 1 ? "正在审核中" : "已通过审核"
                    }`,
                    icon: "none",
                });
                return true;
            }

            return false;
        }

        public async choosePhoto(key: number): Promise<void> {
            if (this.disableClick()) return;

            const [fail, success]: any = await uni.chooseImage({ count: 1 });

            if (fail) return;

            this.certification.images["img" + key] = success.tempFilePaths[0];

            this.$forceUpdate();
        }

        public async chooseIsRent(): Promise<void> {
            if (this.disableClick()) return;

            const [fail, success]: any = await uni.showActionSheet({
                itemList: ["是", "否"],
            });
            if (fail) return;

            this.certification.isRent = !success.tapIndex;
        }

        public async operation(option: AnyObject): Promise<void> {
            if (this.disableClick()) return;
            if (option.type !== "actionSheet") return;

            const [, success]: any = await uni.showActionSheet({
                itemList: option.items,
            });
            if (!success) return;

            this.certification.gender = success.tapIndex;
        }

        public submit(): void {
            type Images = { [key: string]: string };

            let [i, images] = [0, Object.keys(this.certification.images)];

            if (!Object.values(this.certification.images).every((item) => item)) {
                uni.showToast({ title: "请检查相关照片是否上传", icon: "none" });
                return;
            }

            const submitData = (images: Images): void => {
                uni.showLoading({ title: "提交数据中..." });
                const { request, pickers, certification } = this;

                const {
                    routes,
                    color,
                    isRent,
                    carType,
                    numberPlate,
                    route,
                    company,
                    userName,
                    gender,
                } = certification;

                request
                    .get("/api/idcardHandle", {
                        run_id: route.id,
                        company_id: company.id,
                        isRent: +isRent,
                        ...images,
                        color,
                        truename: userName,
                        numberPlate,
                        carType,
                        sex: gender,
                    })
                    .then((res) =>
                        uni.showToast({
                            title: "提交成功",
                            success: () => setTimeout(uni.navigateBack, 1500),
                        })
                    );
            };

            uni.showLoading({ title: "上传图片中..." });

            const uploads: Images = {};

            images.forEach((key, index) => {
                uni.uploadFile({
                    url: $config.API_URL + "/api/upimg",
                    filePath: this.certification.images[key],
                    name: "file",
                    header: { token: Storage.get("userInfo")?.token },
                    success: (res) => {
                        const { data, code, msg: title } = JSON.parse(res.data);
                        if (code !== 1) {
                            uni.showToast({ title, icon: "none" });
                            return;
                        }

                        uploads[key] = data;

                        Object.keys(uploads).length === images.length &&
                            submitData(uploads);
                    },
                    fail: () => {
                        uni.showToast({ title: "图片上传失败", icon: "none" });
                    },
                });
            });
        }
    }
</script>

<style lang="scss" scoped>
    .root {
        .icon-more {
            margin-left: 10rpx;
            width: 10rpx;
            height: 18rpx;
        }
        .icon-warn {
            width: 22rpx;
            height: 22rpx;
        }

        border-bottom: 10rpx solid #eee;

        .transform-identity {
            justify-content: space-between;
            font-size: 36rpx;
            font-weight: 700;
            margin: 30rpx;
        }

        .picker-content {
            padding: 0 40rpx;
            line-height: 100rpx;
            justify-content: space-between;
            .title {
                color: #1b1b1b;
                font-size: 30rpx;
            }
            .value {
                .company {
                    font-size: 20rpx;
                    color: #999;
                }
                .route {
                    padding: 0 12rpx;
                    color: #5487e5;
                    font-size: 28rpx;
                }
            }
        }

        .title {
            color: #1b1b1b;
            font-size: 30rpx;
        }
        .credentials {
            padding: 40rpx 30rpx;
            .images {
                flex-direction: row;
            }
            image {
                width: 46%;
                height: 180rpx;
                margin: 30rpx 15rpx;
                border-radius: 10rpx;
                border-radius: 10rpx;
                background-color: #eee;
            }
            .tips {
                margin-left: 0.6em;
                color: #e60012;
                font-size: 24rpx;
            }
            border-bottom: 10rpx solid #eee;
        }
        .rent-info {
            .explain {
                color: #e60012;
                font-size: 22rpx;
            }
        }

        .rent-info {
            padding: 50rpx 30rpx 20rpx;
        }
        .option {
            justify-content: space-between;
            padding: 30rpx;

            > text {
                color: #666;
                font-size: 30rpx;
            }
            .please-picker {
                color: #5487e5;
                font-size: 26rpx;
            }
            .value {
                font-size: 26rpx;
                color: #5487e5;
                text-align: right;
            }
        }

        .btn-submit {
            background-color: #5487e5;
            border-radius: 10rpx;
            color: #fff;
            margin: 70rpx 20rpx;
        }
    }
</style>